package com.blank.site;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.blank.model.Company;

public class JmqiyeSite implements ISite {

	private String defaulturl;

	public JmqiyeSite() {
		defaulturl = "http://www.jmqiye.com/company/";
	}

	public void addListByUrl(String u) {

		try {
			InputStream is;
			is = Resources.getResourceAsStream("mybatis-config.xml");
			// 建立Session工厂
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
			// 获取Session
			SqlSession session = factory.openSession();
			Elements pages;
			String url = u;

			do {
				Document doc = Jsoup.parse(new URL(url).openStream(), "UTF-8", url);
				Elements elements = doc.select(".list table td[align=left] ul li a");
				pages = doc.select(".list-page a[rel$=nofollow]:contains(下一页)");
				
				url = defaulturl + pages.attr("href");
				Iterator<Element> it = elements.iterator();

				while (it.hasNext()) {
					Element cp = it.next();
					System.out.println(cp.html()); 
					Company company = new Company();
					company.setUrl(cp.select(".fl a").attr("href"));
					company.setSource(defaulturl);
					company.setPhone(cp.select(".tel").html());
					company.setCompanyname(cp.select(".fl a").html());
					company.setAddress(cp.select("dl dd").first()!=null?cp.select("dl dd").first().html():null);
					//session.insert(Company.class.getName() + ".add", company);

				}
			} while (pages.isEmpty() == false);
			session.commit();
			session.close();

		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public void run() {

		Document doc;
		try {
			doc = Jsoup.parse(new URL(defaulturl).openStream(), "UTF-8", defaulturl);
			Elements elements = doc.select("td[width=25%] a");
			for (Element element : elements) {
				//this.addListByUrl(defaulturl + element.attr("href"));
				System.out.println(element.attr("href"));
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
